//
//  ALPictureSelectorController.swift
//  SelectorPicture
//
//  Created by 柴瑞军 on 16/4/23.
//  Copyright © 2016年 myCompany. All rights reserved.
//

import UIKit
import SVProgressHUD
class ALPictureSelectorController: UICollectionViewController {
    let layout = UICollectionViewFlowLayout()
    // 记录用户选择的图片
    private var photos = [UIImage]()
    private let identifier = "dentifier"
    private var maxCount = 6

    init(){
        super.init(collectionViewLayout: layout)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        
        layout.itemSize = CGSize(width: 80, height: 80)
        collectionView?.backgroundColor = UIColor.whiteColor()
        collectionView?.registerClass(ALPictureSelectorCell.self, forCellWithReuseIdentifier: identifier)
        collectionView?.contentInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)

    }
    
}
//MARK: - 实现数据源方法和代理方法

extension ALPictureSelectorController{

    override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return 1
    }
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // 当图片没有到最大张数时,显示图片和一个加号按钮
        // 当图片的数量到达最大张数时,显示的是最大张数
        return photos.count < maxCount ? photos.count + 1 : maxCount
    }
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(identifier, forIndexPath: indexPath) as! ALPictureSelectorCell
        //指定代理
        cell.delegate = self
        cell.backgroundColor  = UIColor.cyanColor()
        
        if indexPath.item < photos.count {
            cell.image = photos[indexPath.item]
        } else {
            // 加号按钮
            cell.setUpAddButton()
        }

        
        return cell
    }
}

//MARK: - 点击cell上的添加图片和删除图片的按钮
extension ALPictureSelectorController: ALPictureSelectorCellDelegate{

    //实现代理方法
    //添加图图片的按钮点击
    func pictureSelectorCellDidClickAddButton(cell: ALPictureSelectorCell) {
       print("\(#function)")
        //TODO:在该方法中进入到系统的图片,添加选择的图片
        //系统的图片选择器
        let selectPictureControl = UIImagePickerController()
        //如果要在打开图片选择控制器的时候做相应的操作,那么就要实现相应的代理方法
        //指定代理
        selectPictureControl.delegate = self
        
        //打开图片选择器
        presentViewController(selectPictureControl, animated: true, completion: nil)
    }
    func pictureSelectorCellDidClickdeleteButton(cell: ALPictureSelectorCell) {
        print("\(#function)")
        //TODO:删除选中的cell中的图片
        //获取cell的indexPath
        let indexPath = collectionView?.indexPathForCell(cell)
        
        photos.removeAtIndex(indexPath!.item)
        
        collectionView?.reloadData()
    }
}
extension ALPictureSelectorController:UIImagePickerControllerDelegate,UINavigationControllerDelegate{

    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?){
        print("选中完成对应的图片后调用")
        //点击选中图片后将选择的图片存储到控制器的图片数组中
        //此处考虑到tableView的优化问题:我们可以将选择的图片绘制到UIImage上,使用的是UIIMage的分类
        //将图片进行等比例缩放,图片显示的模式是scaleASpectFill(此种模式的特点是,将图片根据显示的大小进行等比列填充,超出的部分自动进行裁剪)
        //等等比缩放的宽度newWidth = 300
        let newWidth:CGFloat = 300
        let newHeight:CGFloat = image.size.height/image.size.width*CGFloat(newWidth)
        
        
        image.al_AsyncDrawImage(CGSize(width: newWidth,height: newHeight)) { (image) in
            //将绘制好的图片添加到图片显示的数组中
            self.photos.append(image)
            if self.photos.count == 6{
            SVProgressHUD.showErrorWithStatus("添加图片数量已经达到上限")
            }
            //刷新collectionView让图片进行显示
            self.collectionView?.reloadData()
            
        }
        //选中图片后执行的操作--退出图片选择控制器
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
    //点击取消导航栏的取消按钮后执行的方法
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        print("点击了取消按钮")
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
}
// ---------- cell 相关---------

//设置点击cell上的添加和删除按钮的代理方法
protocol ALPictureSelectorCellDelegate: NSObjectProtocol{

    //定义代理方法
    func pictureSelectorCellDidClickAddButton(cell:ALPictureSelectorCell)
    func pictureSelectorCellDidClickdeleteButton(cell:ALPictureSelectorCell)

}

class ALPictureSelectorCell:UICollectionViewCell{

    var image : UIImage?{
        didSet{
        
           addButton.setImage(image, forState: UIControlState.Normal)
            
            //显示删除按钮
            deleteButton.hidden = false
        }
    }
    
    
    //定义代理属性
    weak var delegate : ALPictureSelectorCellDelegate?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        //添加子控件
        prepareUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //设置加号按钮
    func setUpAddButton(){
    
        addButton.setImage(UIImage(named: "compose_pic_add"), forState: UIControlState.Normal)
        
        //隐藏删除按钮
        deleteButton.hidden = true
    }
    
    private func prepareUI(){
    
        //添加子控件
        contentView.addSubview(addButton)
        contentView.addSubview(deleteButton)
        //设置约束
        addButton.translatesAutoresizingMaskIntoConstraints = false
        deleteButton.translatesAutoresizingMaskIntoConstraints = false
        
        //VFL
        //加号按钮,填充父控件
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[ad]-0-|", options: [], metrics: nil, views: ["ad":addButton]))
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[ad]-0-|", options: [], metrics: nil, views: ["ad":addButton]))
        
        //添加删除按钮的约束
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[db]-0-|", options: [], metrics: nil, views: ["db":deleteButton]))
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[db]", options: [], metrics: nil, views: ["db":deleteButton]))
    }
    //加号按钮可以显示图片
    private lazy var addButton: UIButton = {
    let button = UIButton()
    
        //设置
        button.setImage(UIImage(named:"compose_pic_add"), forState: UIControlState.Normal)
        
        //设置按钮的填充模式
        button.imageView?.contentMode = UIViewContentMode.ScaleAspectFill
        
        //监听点击方法
        button.addTarget(self, action: #selector(ALPictureSelectorCell.didClickAddButton), forControlEvents: UIControlEvents.TouchUpInside)
        
        return button
    }()
    
    //删除按钮
    private lazy var deleteButton: UIButton = {
    
        let button = UIButton()
        
        //设置
        button.setImage(UIImage(named:"compose_photo_close"), forState: UIControlState.Normal)
        //监听点击事件
        button.addTarget(self, action: #selector(ALPictureSelectorCell.didClickDeleteButton), forControlEvents: UIControlEvents.TouchUpInside)
        
        return button
        
    }()
    
    //加号按钮和删除按钮的监听方法
    @objc private func didClickAddButton(){
        delegate?.pictureSelectorCellDidClickAddButton(self)
    }
    @objc private func didClickDeleteButton(){
        delegate?.pictureSelectorCellDidClickdeleteButton(self)
    }
}